<template>
  <div class="settlement-report-list table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList" :showExport="true" fromLocation="结算报告" :exportInfo="exportInfo" :seachData="seachData">
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            :data="tableList"
            :summary="true"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="部门" :width="120" data-index="dept_name" fixed="left" />
              <a-table-column title="运营" :width="70" data-index="salesman_name" fixed="left" />
              <a-table-column title="店铺" :width="160" data-index="shop_name" />
              <a-table-column title="公司" :width="120" data-index="org_name" />
              <a-table-column title="站点" :width="60" data-index="marketplace_id">
                <template #cell="{ record }">
                  <span>{{ $extract(marketPlaceList[record.marketplace_id], 'code') }}</span>
                </template>
              </a-table-column>
              <a-table-column title="月份" :width="80" data-index="month" />
              <a-table-column title="币种" :width="60" data-index="currency" />
              <a-table-column title="销售金额" :width="120" data-index="TYPE_SALES_AMOUNT" :sortable="sortable" align="right" />
              <a-table-column title="返还预留金" :width="120" data-index="TYPE_LAST_RESERVED_AMOUNT" :sortable="sortable" align="right" />
              <a-table-column title="扣除预留金" :width="120" data-index="TYPE_THIS_RESERVED_AMOUNT" :sortable="sortable" align="right" />
              <a-table-column title="差1" :width="120" data-index="cha1str" :sortable="sortable" align="right" />
              <a-table-column title="上月预留金" :width="120" data-index="TYPE_LAST_RESERVED_AMOUNT_V2" :sortable="sortable" align="right" />
              <a-table-column title="本月预留金" :width="120" data-index="TYPE_THIS_RESERVED_AMOUNT_V2" :sortable="sortable" align="right" />
              <a-table-column title="差1" :width="120" data-index="cha2str" :sortable="sortable" align="right" />
              <a-table-column title="退货金额" :width="120" data-index="TYPE_RETURN_AMOUNT" :sortable="sortable" align="right" />
              <a-table-column title="优惠金额" :width="120" data-index="TYPE_PREFERENTIAL_AMOUNT" :sortable="sortable" align="right" />
              <a-table-column title="交易费" :width="120" data-index="TYPE_TRANSACTION_FEE" :sortable="sortable" align="right" />
              <a-table-column title="运费" :width="120" data-index="TYPE_TRANSPORTATION_EXPENSES" :sortable="sortable" align="right" />
              <a-table-column title="广告费" :width="120" data-index="TYPE_ADVERTISING_EXPENSES" :sortable="sortable" align="right" />
              <a-table-column title="秒杀费" :width="120" data-index="TYPE_SECKILL_FEE" :sortable="sortable" align="right" />
              <a-table-column title="订阅费" :width="120" data-index="TYPE_SUBSCRIPTION_FEE" :sortable="sortable" align="right" />
              <a-table-column title="月租费" :width="120" data-index="TYPE_MONTHLY_RENT" :sortable="sortable" align="right" />
              <a-table-column title="评论费" :width="120" data-index="TYPE_COMMENT_FEE" :sortable="sortable" align="right" />
              <a-table-column title="税费" :width="120" data-index="TYPE_CASH_WITHDRAWAL_AMOUNT" :sortable="sortable" align="right" />
              <a-table-column title="其他费用" :width="120" data-index="TYPE_OTHER_EXPENSES" :sortable="sortable" align="right" />
              <a-table-column title="CNY汇率" :width="100" data-index="cny_rate" :sortable="sortable" align="right" />
              <a-table-column title="USD汇率" :width="100" data-index="usd_rate" :sortable="sortable" align="right" />
              <a-table-column title="提现金额" :width="120" data-index="TYPE_PROFIT" :sortable="sortable" align="right" fixed="right" />
              <a-table-column title="人民币" :width="120" data-index="cny_amount_2" :sortable="sortable" align="right" fixed="right" />
              <a-table-column title="美元" :width="120" data-index="usd_amount_2" :sortable="sortable" align="right" fixed="right" />
            </template>
            <template #summary-cell="{ column, record }">
              <p v-if="column.dataIndex == 'sort'">合计</p>
              <p v-else-if="['dept_name', 'salesman_name', 'shop_name', 'org_name', 'month', 'currency', 'cny_rate', 'usd_rate'].includes(column.dataIndex)"></p>
              <p v-else-if="['cny_amount_2'].includes(column.dataIndex)">CNY {{ Number(record[column.dataIndex] || 0).toFixed(2) }}</p>
              <p v-else-if="['usd_amount_2'].includes(column.dataIndex)">USD {{ Number(record[column.dataIndex] || 0).toFixed(2) }}</p>
              <p v-else> {{ Number(record[column.dataIndex] || 0).toFixed(2) }}</p>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.currentPage" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, computed, reactive, PropType } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { FilterTableItem, ExportInfo } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import useBaseDataStore from '@/store/modules/base-data'
  import { SalesmanAggFind } from '@/api/finance/summaryReport'
  import useUserStore from '@/store/modules/user'
  import { marketPlaceList } from '@/utils/globalData'
  import dayjs from 'dayjs'
  import { settlementItemSheetByUser } from '@/utils/exportFiled'

  onMounted(() => {
    getUserList()
    getDeptList()
    setDefaultSearch()
  })

  const searchVal = ref<any>({
    pageSize: 20,
    currentPage: 1,
  })
  const exportInfo: ExportInfo = {
    title: '结算报告按运营汇总',
    type: 'single',
    supportAll: true,
    tabName: '结算报告按运营汇总',
    fieldList: settlementItemSheetByUser,
    supportTemplate: true,
    templateType: 'SETTLEMENT_ITEM_LIST_BY_USER',
    exportApi: 'exportSettlementSalesmanAgg',
    excelName: '运营汇总报告',
  }
  const props = defineProps({
    searchVal: {
      type: Object,
      default: () => {},
    },
    markedtList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    shopList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  })
  const emit = defineEmits(['toSearch'])
  const filterData = ref<any>({})
  const tableLoading = ref(false)
  const useBaseData = useBaseDataStore()
  const tableList = ref<Array<any>>([])
  const userList = ref<Array<any>>([])
  const userStore = useUserStore()
  const tableRef = ref()
  const total = ref(0)
  const seachData = ref<any>({})

  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplace_id_list',
      label: '站点',
      value: ref(props.searchVal.marketplace_id_list ? props.searchVal.marketplace_id_list?.split(',') : null),
      type: 'select_multiple',
      width: 120,
      optionItems: props.markedtList?.map((el: any) => {
        return {
          label: el.marketplaceName,
          value: el.marketplaceId,
        }
      }),
    },
    {
      key: 'seller_id_list',
      label: '全部店铺',
      value: ref(props.searchVal?.seller_id_list ? props.searchVal.seller_id_list.split(',') : null),
      type: 'select_multiple',
      width: 160,
      optionItems: props.shopList?.map((el: any) => {
        return {
          label: el.shopName,
          value: el.sellerId,
        }
      }),
    },
    {
      key: 'dept_id_list',
      label: '部门',
      placeholder: '部门',
      value: ref(),
      type: 'cascader1',
      width: 160,
      optionItems: [],
      attrs: {
        checkStrictly: true,
        fieldNames: { value: 'id', label: 'deptName' },
        placeholder: '部门',
        formatLabel: (options: any) => {
          const labels = options.map((option: any) => option.deptName)
          return labels?.[labels.length - 1]
        },
      },
    },
    {
      key: 'salesman_id',
      label: '运营',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      type: 'date_month',
      key: 'month',
      label: '月份',
      value: ref(`${dayjs().add(-1, 'month').format('YYYY-MM')}`),
      width: 120,
      attrs: {
        defaultValue: '',
      },
    },
  ])
  const isAdmin = computed(() => userStore.admin)
  // 获取部门
  async function getDeptList() {
    await useBaseData.getDeptList()
    filterItem.value[2].optionItems = useBaseData.deptList?.[0]?.children
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    userList.value = useBaseData.userList
    filterItem.value[3].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 初始化查询
  function setDefaultSearch() {
    filterData.value = {
      marketplace_id_list: props.searchVal.marketplace_id_list,
      seller_id_list: props.searchVal.seller_id_list,
    }
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.currentPage = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.currentPage = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }

  // 设置查询条件
  function setSearchval() {
    let _params: any = JSON.parse(JSON.stringify(filterData.value))
    _params.marketplace_id_list = _params.marketplace_id_list ? _params.marketplace_id_list?.split(',') : []
    _params.seller_id_list = _params.seller_id_list ? _params.seller_id_list?.split(',') : []
    _params.dept_id_list = _params.dept_id_list ? _params.dept_id_list?.split(',') : []

    // 非管理员未选择店铺时默认传所有店铺
    if (!isAdmin.value && _params.seller_id_list?.length === 0) {
      _params.seller_id_list = props.shopList?.map((item: any) => item.sellerId) || []
      if (!_params.seller_id_list?.length) {
        Message.error('请选择店铺')
        return
      }
    }

    delete _params.startDate
    delete _params.endDate
    delete _params.dataType

    return _params
  }
  // 获取商品列表
  async function getTableList() {
    tableLoading.value = true
    tableList.value = []
    const _param = {
      needCount: true,
      pageSize: searchVal.value.pageSize,
      currentPage: searchVal.value.currentPage,
      param: setSearchval(),
    }
    tableRef.value.selectAll(false)
    const res: any = await SalesmanAggFind(_param)
    seachData.value = _param.param
    emit('toSearch', filterData.value)
    tableLoading.value = false
    let list = res?.data?.rs?.result || []
    total.value = res?.data?.rs?.rows || 0
    list.forEach((item: any) => {
      item['cny_amount_2'] = item?.cny_amount?.toFixed(2)
      item['usd_amount_2'] = item?.usd_amount?.toFixed(2)
      item['cha1'] = (item?.TYPE_LAST_RESERVED_AMOUNT || 0) + (item?.TYPE_THIS_RESERVED_AMOUNT || 0)
      item['cha2'] = (item?.TYPE_LAST_RESERVED_AMOUNT_V2 || 0) + (item?.TYPE_THIS_RESERVED_AMOUNT_V2 || 0)
      item['cha1str'] = ((item?.TYPE_LAST_RESERVED_AMOUNT || 0) + (item?.TYPE_THIS_RESERVED_AMOUNT || 0)).toFixed(2)
      item['cha2str'] = ((item?.TYPE_LAST_RESERVED_AMOUNT_V2 || 0) + (item?.TYPE_THIS_RESERVED_AMOUNT_V2 || 0)).toFixed(2)
    })
    tableList.value = list
  }
</script>

<style lang="less" scoped>
  .settlement-report-list {
    height: calc(100vh - @menuAndTabHeight);
  }
</style>
